<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">

      <el-form-item label="排班日期">
        <el-date-picker
          v-model="queryParams.dutyDate"
          size="small"
          style="width: 140px"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item label="排班月份">
        <el-date-picker
            v-model="queryParams.month"
            value-format="yyyy-MM-dd"
            type="month"
            placeholder="选择月">
            </el-date-picker>
      </el-form-item>
        <el-form-item label="排班角色">
            <el-select v-model="queryParams.dutyType" style="width: 140px">
                <el-option value="" label="--请选择--"></el-option>
                <el-option value="1" label="部门经理值班"></el-option>
                <el-option value="2" label="部门成员值班"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="过滤历史排班">
            <el-checkbox v-model="queryParams.today"></el-checkbox>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['school:duty:edit']">新增</el-button>
        <el-button
          type="success"
          icon="el-icon-download"
          size="mini"
          @click="handleImport">导入值班</el-button>
        <el-button
          type="primary"
          icon="el-icon-upload2"
          size="mini"
          @click="handleExport">导出值班</el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="handleDateDelete">删除排班</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="AttenceStaList" @selection-change="handleSelectionChange">
      <el-table-column label="值班日期" align="center" prop="dutyDate" :show-overflow-tooltip="true" />
      <el-table-column label="排班角色" align="center" prop="dutyType" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.dutyType==1">部门经理值班</el-tag>
            <el-tag v-if="scope.row.dutyType==2">部门成员值班</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="排班部门" align="center" prop="dutyDept" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.dutyDept==1">启蒙星</el-tag>
            <el-tag v-if="scope.row.dutyDept==2">BCSP</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="老师姓名" align="center" prop="userId" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
              {{getUserName(scope.row.userId)}}
          </template>

      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="dvDesc" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" >
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="换班" placement="top" >
            <el-button
                    size="mini"
                    circle type="success"
                    icon="el-icon-refresh"
                    @click="handleExchange(scope.row)"
                    v-hasPermi="['basedata:bclass:edit']"
            />
          </el-tooltip>
          <el-button
                  size="mini"
                  circle type="success"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['basedata:bclass:edit']"
          />
          <el-button
                  size="mini"
                  circle type="danger"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['basedata:bclass:remove']"
          />
        </template>
      </el-table-column>

    </el-table>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="编辑" :visible="dutyVisible" width="30%">
        <el-form :model="dutyFormData" ref="dutyFormData" label-width="120px" :rules="rules">
            <el-form-item label="老师姓名" prop="userId" required>
                <el-select v-model="dutyFormData.userId" filterable style="width:220px">
                    <el-option :value="item.id" :label="item.username" v-for="(item,index) in userList" :key="index"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="值班日期" prop="dutyDate" required>
                <el-date-picker
                    v-model="dutyFormData.dutyDate"
                    size="small"
                    value-format="yyyy-MM-dd"
                    />
            </el-form-item>
            <el-form-item label="值班角色" prop="dutyType" required>
                <el-select v-model="dutyFormData.dutyType" style="width:220px">
                    <el-option value="1" label="部门经理值班"></el-option>
                    <el-option value="2" label="部门成员值班"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="值班部门" prop="dutyDept" required>
                <el-select v-model="dutyFormData.dutyDept" style="width:220px">
                    <el-option value="1" label="启蒙星"></el-option>
                    <el-option value="2" label="BCSP"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>

    <!--  在读学员信息导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" >
          <el-upload 
            ref="upload"
            :limit="1"
            multiple="multiple"
            name="upload"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"/>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
            </div>
            <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </el-dialog>

        <el-dialog title="换班" :visible="dutyExchangeVisible" width="45%">
            <el-form :model="exchangeFormData" ref="exchangeFormData" :inline="true" class="demo-form-inline" :rules="exchangeRules">
              <el-form-item label="当前老师">
                  <label style="font-size: 16px;color: #4cdf4a;">
                    [{{getUserName(exchangeData.userId)}}]  值班日期：{{exchangeData.dutyDate}}
                  </label>
              </el-form-item>
              <el-form-item label="换班为" prop="id">

                <el-select v-model="exchangeFormData.id" filterable style="width:220px">
                    <el-option :value="item.id+'_'+item.userId" :label="getUserName(item.userId)" v-for="(item,index) in exchangeList" :key="index">
                      <span style="float: left">{{ getUserName(item.userId) }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dutyDate }}</span>
                    </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitDutyExchange">确 定</el-button>
              <el-button @click="closeExchange">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog title="删除排班" :visible.sync="deleteDutyDialog" width="30%">
          <el-form label-position="top">
            <el-form-item label="排班时间段">
              <el-date-picker
                v-model="deleteDateList"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="排班部门">
              <el-select           
                v-model="deleteDept"
                placeholder="请选择"
                clearable
                size="small"
              >
                <el-option
                  v-for="item in deptOption"
                  :key="item.value"
                  :label="item.lable"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitDateDelete" :loading="deleteDutyLoading">确 定</el-button>
            <el-button @click="deleteDutyDialog=false">取 消</el-button>
          </div>
        </el-dialog>
  </div>
</template>



<script>
  // import bargraph from '../../dashboard/AttendanceChart'
  import { getPageList,createOrUpdateSchoolDuty,deleteSchoolDutyById,importTemplate,exportDutyData,updateDutyUser,deleteOtherMonthDuty } from "@/api/school/duty";
  import { listUser } from "@/api/system/user";
  import { getToken } from '@/utils/auth'

  export default {
    name: "duty",
    data(){
      return{
        deleteDutyDialog:false,
        deleteDateList:[],
        deleteDept:undefined,
        deleteDutyLoading:false,
        // 遮罩层
        loading: true,
        dutyExchangeVisible:false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        AttenceStaList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          accessDate: undefined
        },
        userList:[],
        dutyVisible:false,
        dutyFormData:{},
        deptOption:[{
          lable:"启蒙星",
          value:"1",
        },{
          lable:"BCSP",
          value:"2",
        }],
        deleteDateFormData:{
          beginDate:undefined,
          endData:undefined,
          dept:undefined
        },
        rules:{
            userId:[{ required: true, message: '请选择值班老师', trigger: 'blur' }],
            dutyDate:[{ required: true, message: '请选择值班日期', trigger: 'blur' }],
            dutyType:[{ required: true, message: '请选择值班值班角色', trigger: 'blur' }],
            dutyDept:[{ required: true, message: '请选择值班部门', trigger: 'blur' }],
        },
        exchangeRules:{
          id:[{ required: true, message: '请选择换班老师', trigger: 'blur' }]
        },
        deleteRules:{
          beginDate:[{ required: true, message: '请选择日期', trigger: 'blur' }]
        },
        upload: {
        // 是否显示弹出层（学员信息导入）
        open: false,
        // 弹出层标题（学员信息导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的学员信息数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/school/duty/importData",
        
      },
        exchangeList:[],
        exchangeFormData:{},
        exchangeData:{}
      }
    },
    components:{
      // bargraph
    },
    created() {
        this.getUserList(true)
    },
    methods: {
        getUserName(id){
            if(this.userList){
                for(let i = 0; i<this.userList.length; i++){
                    if(id==this.userList[i].id){
                        return this.userList[i].username
                    }
                }
            }
        },
        getUserList(flag){
            const _this = this
            listUser({pageNum: 1,pageSize: 1000}).then(resp=>{
                this.userList = resp.data.list
                if(true){
                    _this.getList();
                }
            })
        },
      /** 查询任务量列表 */
      getList() {
        this.loading = true;
        getPageList(this.queryParams).then(response => {
            this.AttenceStaList = response.data.list;
            this.total = response.data.total;
            this.loading = false;
         
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      handleAdd(){
          this.dutyVisible = true
      },
      submitForm(){
          this.$refs["dutyFormData"].validate((valid) => {
              if(valid){
                  createOrUpdateSchoolDuty(this.dutyFormData).then(resp=>{
                    if(resp.code==200){
                    this.getList()
                    this.$message({  message: '提交成功', type: 'success'});
                    this.dutyFormData={}
                    this.dutyVisible=false
                   }
                })
              }
          })

          
      },
      cancel(){
        this.dutyFormData={}
        this.dutyVisible=false
      },
      handleUpdate(row){
        this.dutyVisible=true
        this.dutyFormData = row
        console.log(this.dutyFormData)
      },
      handleDelete(row){
          deleteSchoolDutyById(row).then(resp=>{
              if(resp.code==200){
                this.$message({  message: '提交成功', type: 'success'});
                this.getList()
                
              }
          })
      },
      // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload1.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open3 = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.message, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 下载模板操作
    importTemplate() {
      importTemplate().then(response => {
        this.fileDownload(response.data, "值班人员模板.xlsx");
      });
    },
     // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 导入按钮操作
    handleImport() {
      this.upload.title = "寄宿学员信息导入";
      this.upload.open = true;
    },
     handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出值班数据项?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
            return exportDutyData(queryParams);
          }).then(response => {
            this.fileDownload(response.data, "值班记录.xlsx");
          }).catch(function() {});
      },
      handleExchange(row){
        this.dutyExchangeVisible = true
        this.exchangeData = row
        getPageList({pageNum: 1, pageSize: 1000, today: true}).then(response => {
              this.exchangeList = response.data.list;
          });
      },
      closeExchange(){
        this.dutyExchangeVisible = false
        this.exchangeFormData={}
      },
      submitDutyExchange(){
        
        this.$refs["exchangeFormData"].validate((valid) => {
            if(valid){
              let formData = {
                oldId:this.exchangeData.id,
                oldUserId: this.exchangeData.userId,
                newId: this.exchangeFormData.id.split("_")[0],
                newUserId: this.exchangeFormData.id.split("_")[1]
              }
              updateDutyUser(formData).then(resp=>{
                if(resp.code==200){
                  this.$message({  message: '提交成功', type: 'success'});
                  this.getList()
                  this.closeExchange()
                }
              })
            }
        })
        

      },
      handleDateDelete(){
        this.deleteDutyDialog = true
        this.deleteDateList=[]
        this.deleteDept = null;
        this.deleteDateFormData = {
          beginDate:null,
          endDate:null,
          dept:null
        }
      },
      submitDateDelete(){
        if(!this.deleteDateList || this.deleteDateList.length==0){
            this.$message({  message: '请选择时间', type: 'warning'});
            return
        }
        this.deleteDateFormData.beginDate = this.deleteDateList[0];
        this.deleteDateFormData.endDate = this.deleteDateList[1];
        this.deleteDateFormData.dept = this.deleteDept;
        this.deleteDutyLoading = true;
        //提交日期删除
        deleteOtherMonthDuty(this.deleteDateFormData).then(resp=>{
          if(resp.date==-1){
            this.$message({  message: resp.message, type: 'error'});
            this.deleteDutyLoading = false;
          }else{
            this.$message({  message: '提交成功', type: 'success'});
            this.handleQuery()
            this.deleteDutyDialog = false
            this.deleteDutyLoading = false;
          }
        })
      }
    },
    
  }
</script>
